package com.yupi.springbootinit.statemachine.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.statemachine.dto.StateMachineConfigQueryRequest;
import com.yupi.springbootinit.statemachine.dto.StateMachineConfigUpdateRequest;
import com.yupi.springbootinit.statemachine.entity.StateMachineConfig;
import com.yupi.springbootinit.statemachine.service.StateMachineConfigService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 状态机配置管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/statemachine/config")
public class StateMachineConfigController {
    
    @Resource
    private StateMachineConfigService stateMachineConfigService;
    
    @Resource
    private UserService userService;
    
    /**
     * 分页查询状态机配置
     */
    @PostMapping("/list")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<IPage<StateMachineConfig>> listConfigs(@RequestBody StateMachineConfigQueryRequest request,
                                                              HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        
        // 设置默认分页参数
        long current = request.getCurrent();
        long size = request.getPageSize();
        ThrowUtils.throwIf(size > 50, ErrorCode.PARAMS_ERROR, "分页大小不能超过50");
        
        IPage<StateMachineConfig> configPage = stateMachineConfigService.queryConfigs(request);
        
        return ResultUtils.success(configPage);
    }
    
    /**
     * 根据实体类型获取配置
     */
    @GetMapping("/type/{entityType}")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<List<StateMachineConfig>> getConfigsByType(@PathVariable String entityType) {
        ThrowUtils.throwIf(entityType == null || entityType.trim().isEmpty(), ErrorCode.PARAMS_ERROR);
        
        List<StateMachineConfig> configs = stateMachineConfigService.getConfigsByStateType(entityType);
        
        return ResultUtils.success(configs);
    }
    
    /**
     * 根据配置键获取配置
     */
    @GetMapping("/key/{configKey}")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<StateMachineConfig> getConfigByKey(@PathVariable String configKey) {
        ThrowUtils.throwIf(configKey == null || configKey.trim().isEmpty(), ErrorCode.PARAMS_ERROR);
        
        StateMachineConfig config = stateMachineConfigService.getConfigByKey(configKey);
        
        return ResultUtils.success(config);
    }
    
    /**
     * 更新配置
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> updateConfig(@RequestBody StateMachineConfigUpdateRequest request,
                                            HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(request.getConfigKey() == null || request.getConfigKey().trim().isEmpty(), 
                          ErrorCode.PARAMS_ERROR, "配置键不能为空");
        ThrowUtils.throwIf(request.getConfigValue() == null || request.getConfigValue().trim().isEmpty(), 
                          ErrorCode.PARAMS_ERROR, "配置值不能为空");
        
        // 获取当前用户
        User loginUser = userService.getLoginUser(httpRequest);
        
        boolean result = stateMachineConfigService.updateConfig(request, loginUser.getId());
        
        return ResultUtils.success(result);
    }
    
    /**
     * 批量更新配置
     */
    @PostMapping("/batch-update")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> batchUpdateConfigs(@RequestBody List<StateMachineConfig> configs,
                                                   HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(configs == null || configs.isEmpty(), ErrorCode.PARAMS_ERROR);
        
        // 获取当前用户
        User loginUser = userService.getLoginUser(httpRequest);
        
        boolean result = stateMachineConfigService.batchUpdateConfigs(configs, loginUser.getId());
        
        return ResultUtils.success(result);
    }
    
    /**
     * 重置配置为默认值
     */
    @PostMapping("/reset/{configKey}")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> resetConfig(@PathVariable String configKey,
                                           HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(configKey == null || configKey.trim().isEmpty(), ErrorCode.PARAMS_ERROR);
        
        // 获取当前用户
        User loginUser = userService.getLoginUser(httpRequest);
        
        boolean result = stateMachineConfigService.resetConfigToDefault(configKey, loginUser.getId());
        
        return ResultUtils.success(result);
    }
    
    /**
     * 获取所有有效配置
     */
    @GetMapping("/active")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<List<StateMachineConfig>> getAllActiveConfigs() {
        List<StateMachineConfig> configs = stateMachineConfigService.getAllActiveConfigs();
        
        return ResultUtils.success(configs);
    }
    
    /**
     * 刷新配置缓存
     */
    @PostMapping("/refresh-cache")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> refreshConfigCache() {
        stateMachineConfigService.refreshConfigCache();
        
        return ResultUtils.success(true);
    }
    
    /**
     * 验证配置值
     */
    @PostMapping("/validate")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> validateConfigValue(@RequestParam String configKey,
                                                   @RequestParam String configValue) {
        ThrowUtils.throwIf(configKey == null || configKey.trim().isEmpty(), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(configValue == null || configValue.trim().isEmpty(), ErrorCode.PARAMS_ERROR);
        
        boolean isValid = stateMachineConfigService.validateConfigValue(configKey, configValue);
        
        return ResultUtils.success(isValid);
    }
    
    /**
     * 根据ID删除配置（软删除）
     */
    @PostMapping("/delete/{id}")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> deleteConfig(@PathVariable Long id,
                                            HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(id == null || id <= 0, ErrorCode.PARAMS_ERROR);
        
        // 获取当前用户
        User loginUser = userService.getLoginUser(httpRequest);
        
        // 软删除配置
        StateMachineConfig config = stateMachineConfigService.getById(id);
        ThrowUtils.throwIf(config == null, ErrorCode.NOT_FOUND_ERROR, "配置不存在");
        
        config.setEnabled(false);
        config.setUpdaterId(loginUser.getId());
        
        boolean result = stateMachineConfigService.updateById(config);
        
        return ResultUtils.success(result);
    }
    
    /**
     * 启用/禁用配置
     */
    @PostMapping("/toggle/{id}")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> toggleConfig(@PathVariable Long id,
                                            @RequestParam Boolean enabled,
                                            HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(id == null || id <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(enabled == null, ErrorCode.PARAMS_ERROR);
        
        // 获取当前用户
        User loginUser = userService.getLoginUser(httpRequest);
        
        StateMachineConfig config = stateMachineConfigService.getById(id);
        ThrowUtils.throwIf(config == null, ErrorCode.NOT_FOUND_ERROR, "配置不存在");
        
        config.setEnabled(enabled);
        config.setUpdaterId(loginUser.getId());
        
        boolean result = stateMachineConfigService.updateById(config);
        
        // 刷新缓存
        if (result) {
            stateMachineConfigService.refreshConfigCache();
        }
        
        return ResultUtils.success(result);
    }
}